package com.zking.forward.index;

import com.zking.dao.UserDao;
import com.zking.entity.User;
import com.zking.util.RedirectMsg;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class Register extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理请求的编码，解决中文乱码
        request.setCharacterEncoding("utf-8");
        //处理响应的编码 ，解决中文乱码
        response.setContentType("text/html;charset=utf-8");

        System.out.println("Register===进来");
        // 获取表单数据
        String userName = request.getParameter("userName");
        String realName = request.getParameter("realName");
        String passWord = request.getParameter("passWord");
        String rePassWord = request.getParameter("rePassWord");
        String sex = request.getParameter("sex");
        String birthyear = request.getParameter("birthyear");
        String birthmonth = request.getParameter("birthmonth");
        String birthday = request.getParameter("birthday");
        String identityCode = request.getParameter("identityCode");
        String email = request.getParameter("email");
        String mobile = request.getParameter("mobile");
        String address = request.getParameter("address");

        // 验证密码是否一致
        if (!passWord.equals(rePassWord)) {
            response.getWriter().write("两次输入的密码不一致");
            return;
        }

        // 构造生日日期
        String birthDate = birthyear + "-" + birthmonth + "-" + birthday;

        // 默认用户类型，1表示普通用户
        int userStatus = 1;

        if(!UserDao.checkUser(userName)){
            request.setAttribute("msg", RedirectMsg.RegisterError);
            request.setAttribute("pageName", RedirectMsg.registerPageName);
            request.setAttribute("url", RedirectMsg.registerUrl);
            request.getRequestDispatcher("redirect.jsp").forward(request, response);
            return;
        }

        // 创建用户对象
        User user = new User(userName, realName, passWord, sex, birthDate, identityCode, email, mobile, address, userStatus);

        // 存储用户信息到数据库
        try {
            UserDao userDao = new UserDao();
            userDao.registerUser(user);
            response.sendRedirect("register-success.jsp");
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("register-fail.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}